#include <sys/types.h>
#include <sys/stat.h>
#include<unistd.h>
#include <fcntl.h>
#include<string.h>
#include<stdlib.h>

#include"mystdio.h"

static MyFile* BuyMyFile(int fd,int flag)
{
    MyFile*myfile=(MyFile*)malloc(sizeof(MyFile));
    if(myfile==NULL)return NULL;
    
    //初始化
    myfile->fileno=fd;
    myfile->flag=flag;
    myfile->bufferlen=0;
    memset(myfile->outbuffer,0,sizeof(myfile->outbuffer));
    myfile->flush_method=LINE_FLUSH;

    return myfile;
}

MyFile* MyFopen(const char* path,const char*mode)
{
    int fd=-1;
    int flag=0;
    if(strcmp(mode,"w")==0)
    {
        flag=O_CREAT|O_TRUNC|O_WRONLY;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"r")==0)
    {
        flag=O_CREAT|O_WRONLY|O_APPEND;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag=O_RDWR;
        fd=open(path,flag);
    }
    if(fd==-1)
        return NULL;
    return BuyMyFile(fd,flag);
}
void MyFclose(MyFile*file)
{
    if(file->bufferlen>0)
        MyFFlush(file);
    close(file->fileno);
}
int MyFwrite(MyFile*file,const char*str,int len)
{
    //1.拷贝数据到缓冲区
    memcpy(file->outbuffer,str,len); 
    file->bufferlen+=len;
    //2.判断是否刷新缓冲区
    if((file->flush_method&LINE_FLUSH)&&file->outbuffer[file->bufferlen-1]=='\n')
        MyFFlush(file);
    if((file->flush_method&FULL_FLUSH)&&file->bufferlen==MAX-1)
        MyFFlush(file);
    if((file->flush_method&NONE_FLUSH))
        MyFFlush(file);

    return len;

}
void MyFFlush(MyFile*file)
{
    write(file->fileno,file->outbuffer,file->bufferlen);
    file->bufferlen=0;
}
